﻿using B.S.Outsourcing.Domain;
using B.S.Outsourcing.ErrorCode;
using B.S.Outsourcing.Infatructrue;
using B.S.Outsourcing.Read.Api.Application.Command.OutsourcingArrivalOrderModel;
using MediatR;

namespace B.S.Outsourcing.Read.Api.Application.CommandHandler.OutsourcingArrivalOrderModel
{
    public class QueryArrivaCommandHandler : IRequestHandler<QueryArrivaCommand, ApiPaging<OutsourcingArrivalOrder>>
    {
        private readonly IBaseRepository<OutsourcingArrivalOrder> baseRepository;
        private readonly DBHelper1 dbHelper;

        public QueryArrivaCommandHandler(IBaseRepository<OutsourcingArrivalOrder> baseRepository, DBHelper1 dbHelper)
        {
            this.baseRepository = baseRepository;
            this.dbHelper = dbHelper;
        }

        public async Task<ApiPaging<OutsourcingArrivalOrder>> Handle(QueryArrivaCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<OutsourcingArrivalOrder> result = new ApiPaging<OutsourcingArrivalOrder>();
            var sql = $"select * from OutsourcingArrivalOrderModel where IsDelete=0";
            if (!string.IsNullOrEmpty(request.FollowOrderNumber))
            {
                sql += $"and FollowOrderNumber={request.FollowOrderNumber}";
            }
            if (!string.IsNullOrEmpty(request.MaterialName))
            {
                sql += $"and MaterialName={request.MaterialName}";
            }
            if (!string.IsNullOrEmpty(request.DocumentCode))
            {
                sql += $"and DocumentCode={request.DocumentCode}";
            }
            if (request.BeginTIme != null)
            {
                sql += $"and CreatedAt>={request.BeginTIme}";
            }
            if (request.EndTime != null)
            {
                sql += $"and EndTime<={request.EndTime}";
            }
            var model = $"{sql} order by OutsourcingArrivalOrderModel.Id offset(({request.pageindex - 1})*{request.pagesize}) rows fetch next {request.pagesize} rows only";
            result.list = dbHelper.GetList<OutsourcingArrivalOrder>(model);
            result.Totalcount = result.list.Count();
            result.Totalpage = (int)Math.Ceiling(result.Totalcount * 1.0 / request.pagesize);
            result.Code = ApiEnums.成功;
            result.Message = "成功";
            return await Task.FromResult(result);
        }
    }
}
